package com.huanzhidadi.java8inaction.chapter5;

import com.alibaba.fastjson2.JSON;
import com.huanzhidadi.java8inaction.model.Trader;
import com.huanzhidadi.java8inaction.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class GroupTest {

    public static void main(String[] args) {

        Trader raoul = new Trader("Raoul", "Cambridge");
        Trader mario = new Trader("Mario", "Milan");
        Trader alan = new Trader("Alan", "Cambridge");
        Trader brian = new Trader("Brian", "Cambridge");

        List<Transaction> transactions = Arrays.asList(
                new Transaction(brian, 2011, 300),
                new Transaction(raoul, 2012, 1000),
                new Transaction(raoul, 2011, 400),
                new Transaction(mario, 2012, 710),
                new Transaction(mario, 2012, 700),
                new Transaction(alan, 2012, 950)
        );

        // 分组1
        // groupMethod1(transactions);

        // 分组2
        groupMethod2(transactions);

    }

    private static void groupMethod1(List<Transaction> transactions) {
        Map<Integer, List<Transaction>> transationByYear = new HashMap<>();
        for (Transaction transaction : transactions) {
            Integer year = transaction.getYear();
            List<Transaction> temp = transationByYear.get(year);
            if (CollectionUtils.isEmpty(temp)) {
                temp = new ArrayList<>();
                transationByYear.put(year, temp);
            }
            temp.add(transaction);
        }
        log.info(JSON.toJSONString(transationByYear));
    }

    private static void groupMethod2(List<Transaction> transactions) {
        Map<Integer, List<Transaction>> transationByYear = transactions.stream().
                collect(Collectors.groupingBy(Transaction::getYear));
        log.info(JSON.toJSONString(transationByYear));
    }
}
